<template>
  <el-dialog v-model="dialogVisible" title="导入" :close-on-click-modal="false" append-to-body width="600"
    class="editDialog" align-center>
    <el-form label-width="120px" v-if="dialogVisible && step === 1">
      <el-form-item label="模板" required>
        <div class="downloadTemplate">
          <span class="text">{{ param.fileName }}</span>
          <el-link :underline="false" type="primary" @click="fileDownload()">下载</el-link>
        </div>
      </el-form-item>
      <el-form-item label="上传文件" required>
        <div class="innerItem">
          <div class="uploadFile">
            <el-input type="text" v-model="selectedFile.name"></el-input>
            <input type="file" class="input" ref="ref" accept=".xls, .xlsx" @change="handleFileChange" />
            <!-- </input> -->
            <el-button type="primary">上传文件</el-button>
          </div>
          <div class="tip">
            <i class="if-font-error-circle-filled"></i>
            <div class="text">
              <p>下载导入模板，按要求填写信息。</p>
              <p>模板中第一行为演示数据，录入数据时请删除！</p>
            </div>
          </div>
        </div>
      </el-form-item>
    </el-form>
    <div class="inLoading" v-else-if="step === 2">
      <i class="if-font-LoadingOutlined"></i>
      <div class="text">导入中</div>
    </div>
    <div class="result" v-else-if="step === 3 && result">
      <template v-if="result.status"><i class="if-font-checkmark-circle-filled success"></i>
        <div class="text">{{ result.msg }}</div>
      </template>
      <template v-else>
        <template v-if="result.errorCount">
          <div class="title success">
            导入成功: {{ result.successCount }} 条
          </div>
          <div class="title">
            导入失败,共{{ result.errorCount }}条，原因如下：<el-button type="primary" size="small" @click="copyResult"
              class="copyResult">复制</el-button>
          </div>
          <div class="inner">
            <el-scrollbar>
              <template v-for="item in result.msg.split('\\d')">
                {{ item }}<br />
              </template>
            </el-scrollbar>
          </div>
        </template>
        <template v-else>
          <i class="if-font-error-circle-filled fail"></i>
          <div class="text">导入失败: {{ result.msg }}</div>
        </template>
      </template>
    </div>
    <div class="opt">
      <template v-if="step === 1">
        <el-button size="large" @click="dialogVisible = false" auto-insert-space>取消</el-button>
        <el-button type="primary" size="large" auto-insert-space @click="handleFileImport">
          确定</el-button>
      </template>
      <template v-if="step === 3">
        <el-button type="primary" size="large" v-if="result && result.status" auto-insert-space @click="confirmSuccess">
          确定</el-button>
        <el-button type="primary" size="large" auto-insert-space class="backBtn" v-if="result && !result.status"
          @click="backToImport">
          返回重选导入</el-button>
      </template>
    </div>
  </el-dialog>
</template>

<script setup>
import { ref } from "vue";
import { baseTemplate, baseImport } from "@/utils/requests.js";
import { ElMessage } from "element-plus";
const emit = defineEmits(["confirm"]);

let step = ref(1);
let result = ref();

let dialogVisible = ref(false);


let param = ref({ 
});

let selectedFile = ref({
  name: "",
}); 

const openDialog = (data) => { 
  step.value = 1;
 
  param.value = { ...data };
 
  selectedFile.value = "";

  dialogVisible.value = true;
};

const handleFileChange = (event) => {
  const file = event.target.files[0]; //.raw
  selectedFile.value = file;
  const { name, size } = file;

  const m5 = size / 1024 / 1024;
  if (m5 > 5) {
    MessagePlugin.error("上传文件不能超过，5M");
    return;
  }

  const is_type = name.indexOf(".xls") != -1 || name.indexOf(".xlsx") != -1;

  if (!is_type) {
    MessagePlugin.error("上传文件必须是，.xls和.xlsx文件");
    return;
  }
};
const handleFileImport = (code) => {
  fileImport();
};

const fileDownload = () => {
  baseTemplate({
    ...param.value
  }).then((data) => {
    if (data) { 
      const url = window.URL.createObjectURL(new Blob([data]));
      const link = document.createElement("a");
      link.href = url;
      link.setAttribute("download", param.value.fileName || "导入模板.xlsx"); //or any other extension
      document.body.appendChild(link);

      link.click();

      document.body.removeChild(link);
      window.URL.revokeObjectURL(link.href);
    }
  });
};
const fileImport = () => {
  step.value = 2;
  baseImport({
    ...param.value,
    file: selectedFile.value,
  }).then((data) => {
    if (data) {

      result.value = data;
      step.value = 3;
    } else {
      step.value = 1;
    }
  });
};

const confirmSuccess = () => {
  emit("confirm");
  dialogVisible.value = false;
};

const backToImport = () => {
  step.value = 1;
};

const copyResult = () => {
  const textarea = document.createElement("textarea");
  textarea.value = result.value.msg.split("\\d").join("\n");
  document.body.appendChild(textarea);
  textarea.select();
  document.execCommand("copy");
  document.body.removeChild(textarea);

  ElMessage.success("复制成功！");
};

defineExpose({ openDialog });
</script>

<style scoped lang="scss">
.downloadTemplate {
  display: flex;
  align-items: center;

  .text {
    margin-right: 10px;
  }
}

.innerItem {
  flex-direction: column;
  width: 360px;

  .uploadFile {
    display: flex;
    position: relative;

    .input {
      position: absolute;
      opacity: 0;
      top: 0;
      right: 0;
      bottom: 0;
      left: 0;
      width: 100%;
    }
  }

  .tip {
    margin-top: 10px;
    display: flex;
    border: 1px solid rgba(250, 196, 80, 1);
    border-radius: 3px;
    background: rgba(254, 249, 237, 1);
    color: #7f7f7f;
    padding: 10px;

    i {
      flex: 0 0 20px;
      font-size: 16px;
      color: rgba(250, 196, 80, 1);
    }

    p {
      margin: 0;
      line-height: 20px;
      font-size: 12px;
    }
  }
}

.inLoading {
  padding-top: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;

  i {
    font-size: 30px;
    color: #409eff;
    margin-bottom: 15px;
    animation: rotate 1s linear infinite;
  }
}

@keyframes rotate {
  0% {
    transform: rotate(0deg);
  }

  100% {
    transform: rotate(360deg);
  }
}

.result {
  text-align: center;

  i {
    font-size: 40px;
    margin-bottom: 10px;

    &.success {
      color: #67c23a;
    }

    &.fail {
      color: #e6a23c;
    }

    +.text {
      text-align: center;
    }
  }

  .title {
    display: flex;
    align-items: center;
    line-height: 32px;
    font-size: 16px;
    color: #f56c6c;
    justify-content: space-between;

    &.success {
      justify-content: center;
      font-weight: bold;
      color: #409eff;
    }
  }

  .text {
    line-height: 26px;
  }

  .inner {
    line-height: 26px;
    height: 150px;
    text-align: left;
  }
}

.opt {
  margin-top: 50px;
  text-align: right;

  .backBtn {
    width: 50%;
    margin: 0 auto;
    display: block;
  }
}
</style>
